const CarnumDatasDeptType = appRequire('model/desktop/CarnumDatasDeptType');
const PageResultVo = appRequire('vo/PageResultVo.js');
class CarnumDatasDeptTypeSequelizeDao {
  constructor() {

  }
  static async create() {
    await CarnumDatasDeptType.sync();
  }
  static async saveOne(carnumDatasDeptType) {
    try {
      await CarnumDatasDeptType.create(carnumDatasDeptType);
    } catch (error) {
      throw new Error(error);
    }
  }
  static async updateOne(carnumDatasDeptType) {
    try {
      await CarnumDatasDeptType.update(carnumDatasDeptType,{where:{id:carnumDatasDeptType.id}});
    } catch (error) {
      throw new Error(error);
    } 
  }
  static async deleteById(id) {
    try {
      await CarnumDatasDeptType.destroy({where:{id}});
    } catch (error) {
      throw new Error(error);
    }
  }
  static async deleteMany(ids) {
    try {
      ids = ids.split(",");
      console.log(ids);
      await CarnumDatasDeptType.destroy({where:{id:ids}});
    } catch (error) {
      throw new Error(error);
    }
  }
  /**
   * 定制化查找字段
   * @param {*} id 
   */
  static async findOne(id) {
    try {
      let data = await CarnumDatasDeptType.findOne({
        where:{
          id
        },
        raw:true,
        attributes: { exclude: [] },
      });
      return data;
    } catch (error) {
      throw new Error(error);
    } 
  }
  static async findById(id) {
    try {
      let data = await CarnumDatasDeptType.findOne({
        where:{
          id
        },
        raw:true,
        attributes: { exclude: [] },
      });
      return data;
    } catch (error) {
      throw new Error(error);
    } 
  }
  static async findAll() {
    try {
      let data = await CarnumDatasDeptType.findAll({
        raw:true,
        attributes: ['id',['dept_name','deptName'],'sort'],
      });
      return data;
    } catch (error) {
      throw new Error(error);
    } 
  }
  static async findByPage(page) {
    try {
      let offset = (page.pageNum-1)*page.pageSize;
      let limit = page.pageSize;
      let where = {};
      //动态拼装sql的where条件
      if(page.searchParams){
        if(page.searchParams.deptName){
          where.dept_name = {
            [Op.like]: `%${page.searchParams.deptName}%`,
          }
        }
      }
      let result = await CarnumDatasDeptType.findAndCountAll({
        where,offset,limit,raw:true,attributes:{exclude:[]},order:[["id","DESC"]]
      })
      console.log(result)
       return PageResultVo.success('success',result.count,result.rows);
    } catch (error) {
      throw new Error(error);
    } 
  } 
}
module.exports = CarnumDatasDeptTypeSequelizeDao;